package com.major.dawn.leetCode.string;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class CountCharNumber extends RecursiveTask<Integer> {

    private final char[] chars;

    private final char achar;

    private static final int threshold = 4;

    public CountCharNumber(char[] chars, Character achar) {
        this.chars = chars;
        this.achar = achar;
    }

    @Override
    protected Integer compute() {
        int count = 0;
        int length = chars.length;

        if (length <= threshold) {
            for (int i = 0; i < length; i++) {
                if (chars[i] == achar) {
                    count++;
                }
            }
        } else {
            int middle = length / 2;
            char[] left = new char[middle];
            System.arraycopy(chars, 0, left, 0, middle);
            CountCharNumber leftCountCharNumber = new CountCharNumber(left, achar);
            char[] right = new char[length - middle];
            System.arraycopy(chars, middle, right, 0, length - middle);
            CountCharNumber rightCountCharNumber = new CountCharNumber(right, achar);
            leftCountCharNumber.fork();
            rightCountCharNumber.fork();
            Integer leftNum = leftCountCharNumber.join();
            Integer rightNum = rightCountCharNumber.join();
            count = leftNum + rightNum;

        }
        Thread thread = Thread.currentThread();
        System.out.println(thread);

        return count;

    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        String cur = "SSDFFFFDDDDDDDFGBB";
        ForkJoinTask<Integer> task = forkJoinPool.submit(new CountCharNumber(cur.toCharArray(), 'D'));
        Integer integer = task.get();
        System.out.println(integer);
    }
}
